<template>
  <div class="content-area">
    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">护士姓名</div>
          <el-input
            v-model="filters.nurse_name"
            placeholder="请输入护士姓名"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">护士工号</div>
          <el-input
            v-model="filters.work_id"
            placeholder="请输入护士工号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">所属科室</div>
          <el-select
            v-model="filters.department_id"
            placeholder="请选择科室"
            clearable
          >
            <el-option
              v-for="dept in filterQueryDepartmentTitleOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">职称</div>
          <el-select
            v-model="filters.professional_id"
            placeholder="请选择职称"
            clearable
          >
            <el-option
              v-for="prof in professionalOptions"
              :key="prof.value"
              :label="prof.label"
              :value="prof.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">状态</div>
          <el-select
            v-model="filters.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="在职" :value="1" />
            <el-option label="休假" :value="2" />
            <el-option label="离职" :value="3" />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchNurses">查询</el-button>
        <el-button type="success" @click="showAddNurseDialog">
          <el-icon><Plus /></el-icon>
          新增护士
        </el-button>
      </div>
    </div>

    <!-- 护士表格 -->
    <div class="nurse-table">
      <div class="table-header">
        <div class="table-title">护士列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Document /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table :data="nurses" style="width: 100%" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="work_id" label="工号" width="100" />
        <el-table-column label="护士信息" min-width="180">
          <template #default="{ row }">
            <div class="nurse-info">
              <div class="nurse-avatar">
                <el-avatar :size="40" :src="row.nurse_avatar" />
              </div>
              <div>
                <div>{{ row.nurse_name }}</div>
                <div style="font-size: 12px; color: #909399">
                  {{ formatTitle(row.professional_id) }} ·
                  {{ row.department_name }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            {{ formatSex(row.sex) }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="work_years" label="工作年限" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 1
                  ? 'success'
                  : row.status === 2
                  ? 'warning'
                  : 'info'
              "
              size="small"
            >
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewNurseDetails(row)"
                >详情</el-button
              >
              <el-button
                size="small"
                type="primary"
                @click="editNurseHandle(row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteNurseHandle(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          :page-count="pagination.pageTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 新增/编辑护士对话框 -->
  <el-dialog
    v-model="nurseDialog.visible"
    :title="nurseDialog.isEdit ? '编辑护士信息' : '新增护士'"
    width="750px"
    :destroy-on-close="false"
  >
    <el-form
      :model="nurseForm"
      label-width="100px"
      :rules="nurseRules"
      ref="nurseFormRef"
    >
      <div style="display: flex; gap: 20px">
        <div style="flex: 1">
          <!-- 护士照片上传 -->
          <el-form-item label="护士照片" prop="nurse_avatar">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarChange"
            >
              <el-avatar
                :size="60"
                :src="nurseForm.nurse_avatar || defaultAvatar"
                style="cursor: pointer"
              />
              <div style="font-size: 12px; color: #909399; margin-top: 4px">
                点击更换
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="护士工号" prop="work_id">
            <el-input
              v-model="nurseForm.work_id"
              placeholder="请输入护士工号"
              :disabled="nurseDialog.isEdit"
            />
          </el-form-item>
          <el-form-item label="护士姓名" prop="nurse_name">
            <el-input
              v-model="nurseForm.nurse_name"
              placeholder="请输入护士姓名"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="nurseForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number
              v-model="nurseForm.age"
              :min="18"
              :max="65"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="nurseForm.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="科室类型" prop="department_type">
            <el-select
              v-model="nurseForm.department_type"
              placeholder="请先选择科室类型"
              clearable
              @change="onDialogDepartmentTypeChange"
            >
              <el-option
                v-for="type in departmentTypes"
                :key="type.department_type_id"
                :label="type.department_type_name"
                :value="type.department_type_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属科室" prop="department_id">
            <el-select
              v-model="nurseForm.department_id"
              placeholder="请选择科室"
            >
              <el-option
                v-for="dept in filteredDepartmentOptions"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <div style="flex: 1">
          <el-form-item label="职称" prop="professional_id">
            <el-select
              v-model="nurseForm.professional_id"
              placeholder="请选择职称"
            >
              <el-option
                v-for="prof in professionalOptions"
                :key="prof.value"
                :label="prof.label"
                :value="prof.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工作年限" prop="work_years">
            <el-input-number
              v-model="nurseForm.work_years"
              :min="0"
              :max="50"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="nurseForm.status" placeholder="请选择状态">
              <el-option label="在职" :value="1" />
              <el-option label="休假" :value="2" />
              <el-option label="离职" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="账户" prop="username">
            <!-- 编辑时只展示，新增时展示输入框 -->
            <template v-if="nurseDialog.isEdit">
              <div style="line-height: 36px">{{ nurseForm.username }}</div>
            </template>
            <template v-else>
              <el-input v-model="nurseForm.username" placeholder="请输入账户" />
            </template>
          </el-form-item>
          <el-form-item label="密码" prop="userpass" v-if="!nurseDialog.isEdit">
            <el-input
              v-model="nurseForm.userpass"
              placeholder="请输入密码"
              type="password"
            />
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input
              v-model="nurseForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入护士简介"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="nurseDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitNurseForm">确认</el-button>
    </template>
  </el-dialog>

  <!-- 右侧抽屉：护士详情 -->
  <el-drawer
    v-model="detailDrawer.visible"
    direction="rtl"
    size="600px"
    with-header
    :destroy-on-close="false"
  >
    <template #header>
      <div class="drawer-custom-header">
        <h3>护士详情</h3>
      </div>
    </template>

    <div class="drawer-content-wrapper">
      <!-- 顶部个人信息卡片 -->
      <div class="staff-profile-card">
        <div class="profile-header">
          <el-avatar
            :size="80"
            :src="detailInfo.nurse_avatar || defaultAvatar"
            class="profile-avatar"
          />
          <div class="profile-info">
            <h2 class="staff-name">{{ detailInfo.nurse_name }}</h2>
            <div class="staff-meta">
              <el-tag type="success" size="small">
                {{ formatTitle(detailInfo.professional_id) }}
              </el-tag>
              <span class="work-id">{{ detailInfo.work_id }}</span>
            </div>
            <div class="staff-status">
              <el-tag :type="statusTagType(detailInfo.status)" size="small">
                {{ formatStatus(detailInfo.status) }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 详细信息区域 -->
      <div class="detail-sections">
        <!-- 基本信息 -->
        <div class="detail-section">
          <div class="section-header">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </div>
          <div class="section-content">
            <div class="info-grid">
              <div class="info-item">
                <label>性别</label>
                <span>{{ formatSex(detailInfo.sex) }}</span>
              </div>
              <div class="info-item">
                <label>年龄</label>
                <span>{{ detailInfo.age || "未填写" }}岁</span>
              </div>
              <div class="info-item">
                <label>联系电话</label>
                <span>{{ detailInfo.phone || "未填写" }}</span>
              </div>
              <div class="info-item">
                <label>工作年限</label>
                <span class="highlight"
                  >{{ detailInfo.work_years || 0 }}年</span
                >
              </div>
              <div class="info-item">
                <label>所属科室</label>
                <span>{{
                  detailInfo.departmentName ||
                  getDepartmentLabel(detailInfo.department_id)
                }}</span>
              </div>
              <div class="info-item">
                <label>职称</label>
                <span class="highlight">{{
                  formatTitle(detailInfo.professional_id)
                }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 账户信息 -->
        <div class="detail-section">
          <div class="section-header">
            <el-icon><Key /></el-icon>
            <span>账户信息</span>
          </div>
          <div class="section-content">
            <div class="info-grid">
              <div class="info-item">
                <label>登录账户</label>
                <span class="username">{{
                  detailInfo.username || "未设置"
                }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 个人简介 -->
        <div class="detail-section">
          <div class="section-header">
            <el-icon><Briefcase /></el-icon>
            <span>个人简介</span>
          </div>
          <div class="section-content">
            <div class="info-item-full">
              <div class="info-content description-text">
                {{ detailInfo.description || "暂无简介" }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="detailDrawer.visible = false">关闭</el-button>
        <el-button type="primary" @click="openEditFromDrawer">
          <el-icon><Edit /></el-icon>
          编辑信息
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
// 导入后端接口
import {
  uploadAvatar,
  addNurse,
  editNurse,
  getDepartmentList,
  getNurseProfessionList,
  getNursePagerDataBySearch,
  getDepartmentTypeList,
} from "@/api/api";
import { t } from "@wangeditor/editor";

const router = useRouter();
const store = useStore();

const username = ref(store.state.user?.username || "管理员");

// 过滤器
const filters = reactive({
  nurse_name: "",
  work_id: "",
  department_id: "",
  department_type: "", // 新增：科室类型筛选
  professional_id: "",
  status: "",
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageTotal: 0,
  total: 0,
});

const departmentTypes = ref([]); // 存储科室类型列表
const filteredDepartmentOptions = ref([]); // 存储根据科室类型筛选后的科室列表
// 科室选项
const departmentOptions = ref([]);
// 护士职称选项
const professionalOptions = ref([]);

// 护士数据
const nurses = ref([]);

// 全局加载状态，用于控制表格的 loading 动画
const loading = ref(false);

// 护士对话框相关
const nurseDialog = reactive({
  visible: false,
  isEdit: false,
});

// 抽屉状态与详情对象
const detailDrawer = reactive({
  visible: false,
});

const detailInfo = reactive({
  nurse_id: null,
  work_id: "",
  nurse_name: "",
  nurse_avatar: "",
  professional_id: null,
  sex: null,
  age: null,
  phone: "",
  work_years: null,
  status: null,
  department_id: null,
  departmentName: "",
  description: "",
  username: "",
});

// 默认头像读取assets目录下的图片
const defaultAvatar = require("@/assets/img/default-avatar.jpeg");

const nurseForm = reactive({
  nurse_id: null,
  work_id: "",
  nurse_name: "",
  nurse_avatar: "",
  professional_id: 3,
  sex: 2,
  age: 25,
  phone: "",
  work_years: 0,
  shift: "day",
  status: 1,
  department_id: 1,
  department_type: 1, // 新增：科室类型，默认临床科室
  description: "",
  username: "",
  userpass: "",
});

// 将 nurseRules 改为 computed，根据是否为编辑状态动态生成规则
const nurseRules = computed(() => {
  const rules = {
    work_id: [{ required: true, message: "请输入护士工号", trigger: "blur" }],
    nurse_name: [
      { required: true, message: "请输入护士姓名", trigger: "blur" },
    ],
    sex: [{ required: true, message: "请选择性别", trigger: "change" }],
    age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
    phone: [
      { required: true, message: "请输入联系电话", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    department_type: [
      // 新增
      { required: true, message: "请先选择科室类型", trigger: "change" },
    ],
    department_id: [
      { required: true, message: "请选择科室", trigger: "change" },
    ],
    professional_id: [
      { required: true, message: "请选择职称", trigger: "change" },
    ],
    work_years: [
      { required: true, message: "请输入工作年限", trigger: "blur" },
    ],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
    // username / userpass 仅在 新增 模式下需要校验
  };
  if (!nurseDialog.isEdit) {
    rules.username = [
      { required: true, message: "请输入账户", trigger: "blur" },
    ];
    rules.userpass = [
      { required: true, message: "请输入密码", trigger: "blur" },
    ];
  }
  return rules;
});

// 过滤搜索条件中的科室信息
const filterQueryDepartmentTitleOptions = computed(() => {
  return departmentOptions.value.filter(
    (dept) => dept.department_type === 1 || dept.department_type === 2
  );
});

// 对话框中科室类型变化处理
const onDialogDepartmentTypeChange = (typeId) => {
  // 清空已选的科室
  nurseForm.department_id = "";

  // 根据科室类型过滤科室选项
  if (!typeId) {
    filteredDepartmentOptions.value = departmentOptions.value;
  } else {
    // 过滤科室（确保科室数据中有 department_type 字段）
    filteredDepartmentOptions.value = departmentOptions.value.filter(
      (dept) => Number(dept.department_type) === Number(typeId)
    );

    // 如果过滤后有选项，设置默认选中第一个
    if (filteredDepartmentOptions.value.length > 0) {
      nurseForm.department_id = filteredDepartmentOptions.value[0].value;
    }
  }
};

// 新增：根据科室ID自动选择科室类型的函数
const autoSelectDepartmentType = (departmentId) => {
  if (!departmentId) return "";

  // 在科室选项中查找对应的科室
  const department = departmentOptions.value.find(
    (dept) => Number(dept.value) === Number(departmentId)
  );

  if (department && department.department_type) {
    return department.department_type;
  }

  return "";
};

const nurseFormRef = ref(null);

// 获取科室列表
const loadDepartments = async () => {
  try {
    const res = await getDepartmentList();
    if (res && res.code == 200) {
      departmentOptions.value = res.data.map((d) => ({
        value: Number(d.department_id),
        label: d.department_name,
        department_type: d.department_type, // 确保获取科室类型字段
      }));
    }
  } catch (e) {
    console.error("加载科室失败", e);
    ElMessage.error("加载科室失败");
  }
};

// 获取护士职称列表
const loadProfessionalTitles = async () => {
  try {
    const res = await getNurseProfessionList();
    // 兼容 resp 或 resp.data 结构
    const payload = res && res.data ? res.data : res;
    if (payload && payload.code === 200 && Array.isArray(payload.data)) {
      professionalOptions.value = payload.data.map((p) => ({
        value: Number(p.professional_id),
        label: p.professional_title,
      }));
    } else if (Array.isArray(payload)) {
      professionalOptions.value = payload.map((p) => ({
        value: Number(p.professional_id),
        label: p.professional_title,
      }));
    } else {
      console.warn("getNurseProfessionList 返回格式异常：", payload);
    }
  } catch (e) {
    console.error("加载职称失败", e);
    ElMessage.error("加载职称失败");
  }
};

const resetFilters = () => {
  filters.nurse_name = "";
  filters.work_id = "";
  filters.department_id = "";
  filters.professional_id = "";
  filters.status = "";
  loadNurses();
};

const searchNurses = () => {
  pagination.currentPage = 1;
  loadNurses();
};

// 分页提交请求数据
const loadNurses = async () => {
  const params = {
    nurse_name: filters.nurse_name,
    work_id: filters.work_id,
    department_id: filters.department_id,
    professional_id: filters.professional_id,
    status: filters.status,
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
  };
  loading.value = true;
  try {
    let res = await getNursePagerDataBySearch(params);
    if (res && res.code == 200) {
      nurses.value = res.data.data;
      pagination.pageTotal = res.data.pageTotal;
      pagination.total = res.data.total || 0;
    } else {
      // 兼容可能的不同返回结构或错误码
      console.warn("getNursePagerDataBySearch 返回异常：", res);
    }
  } catch (e) {
    console.error("加载护士列表失败", e);
    ElMessage.error("加载护士列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadNurses();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadNurses();
};

const viewNurseDetails = (nurse) => {
  // 以传入的 nurse 为准填充详情
  Object.assign(detailInfo, {
    nurse_id: nurse.nurse_id ?? null,
    work_id: nurse.work_id ?? "",
    nurse_name: nurse.nurse_name ?? "",
    nurse_avatar: nurse.nurse_avatar ?? "",
    professional_id: nurse.professional_id ?? nurse.professionalId ?? null,
    sex: nurse.sex ?? 2,
    age: nurse.age ?? 25,
    phone: nurse.phone ?? "",
    work_years: nurse.work_years ?? 0,
    shift: nurse.shift ?? "day",
    status: nurse.status ?? 1,
    department_id: nurse.department_id ?? null,
    departmentName: nurse.department_name ?? "",
    description: nurse.description ?? "",
    username: nurse.username ?? "",
  });

  // 若没有 departmentName，尝试从已加载的科室里匹配
  if (!detailInfo.departmentName && detailInfo.department_id) {
    detailInfo.departmentName = getDepartmentLabel(detailInfo.department_id);
  }

  detailDrawer.visible = true;
};

// 从抽屉直接进入编辑（复用已有 editNurseHandle）
const openEditFromDrawer = () => {
  // 传入 detailInfo 的浅拷贝，避免双向影响显示（edit 会覆盖 nurseForm）
  editNurseHandle({ ...detailInfo });
  detailDrawer.visible = false;
};

const editNurseHandle = (nurse) => {
  // 将后端返回的 nurse 信息填入表单，保留 username（不可修改），清空密码字段
  Object.assign(nurseForm, {
    ...nurse,
    userpass: "",
    // 自动设置科室类型
    department_type: autoSelectDepartmentType(nurse.department_type) || 1, // 确保有科室类型字段
  });

  // 根据科室类型过滤显示对应的科室
  const typeId = nurseForm.department_type;
  filteredDepartmentOptions.value = departmentOptions.value.filter(
    (dept) => Number(dept.department_type) === Number(typeId)
  );

  nurseDialog.isEdit = true;
  nurseDialog.visible = true;
};

const deleteNurseHandle = (nurse) => {
  ElMessageBox.confirm(
    `确定要删除护士 ${nurse.nurse_name} 吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 模拟删除操作
      nurses.value = nurses.value.filter((n) => n.nurse_id !== nurse.nurse_id);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const beforeAvatarUpload = (file) => {
  // 检查文件类型
  const fileExt = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
  const isValidType = [".jpg", ".jpeg", ".png"].includes(fileExt);

  // 检查文件大小（4MB）
  const isLt2M = file.size / 1024 / 1024 < 4;

  if (!isValidType) {
    ElMessage.error("只支持JPG、JPEG和PNG格式的图片！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过2MB！");
    return false;
  }
  return true;
};

const handleAvatarChange = async (params) => {
  try {
    const formData = new FormData();
    formData.append("file", params.file);
    const res = await uploadAvatar(formData);
    if (res.code == 200) {
      nurseForm.nurse_avatar = res.data;
      ElMessage.success("头像上传成功");
    } else {
      ElMessage.error("头像上传失败");
    }
  } catch (e) {
    ElMessage.error("头像上传失败");
  }
};

const showAddNurseDialog = () => {
  // 重置表单
  Object.assign(nurseForm, {
    nurse_id: null,
    work_id: "",
    nurse_name: "",
    nurse_avatar: "",
    professional_id: 3,
    sex: 2,
    age: 25,
    phone: "",
    work_years: 0,
    shift: "day",
    status: 1,
    department_id: 1,
    department_type: 1, // 默认选择临床科室
    description: "",
    username: "",
    userpass: "",
  });
  // 新增：初始化过滤临床科室相关的科室选项
  onDialogDepartmentTypeChange(1);

  nurseDialog.isEdit = false;
  nurseDialog.visible = true;
};

const submitNurseForm = async () => {
  try {
    await nurseFormRef.value.validate();

    // 准备要发送给后端的 payload，确保数值字段为 Number 类型
    const payload = {
      nurse_id: nurseForm.nurse_id, // 编辑需要 id
      work_id: nurseForm.work_id,
      nurse_name: nurseForm.nurse_name,
      nurse_avatar: nurseForm.nurse_avatar || defaultAvatar,
      professional_id: Number(nurseForm.professional_id),
      sex: Number(nurseForm.sex),
      age: Number(nurseForm.age),
      phone: nurseForm.phone,
      work_years: Number(nurseForm.work_years),
      shift: nurseForm.shift,
      status: Number(nurseForm.status),
      department_id: Number(nurseForm.department_id),
      description: nurseForm.description,
      username: nurseForm.username,
      // userpass 仅在新增时发送（编辑时通常不修改密码）
      ...(nurseDialog.isEdit ? {} : { userpass: nurseForm.userpass }),
    };

    if (nurseDialog.isEdit) {
      // 调用后端编辑接口
      let resp;
      try {
        resp = await editNurse(payload);
      } catch (err) {
        if (err && err.response) {
          const msg =
            err.response.data?.message ||
            err.response.data?.msg ||
            `编辑失败（${err.response.status}）`;
          ElMessage.error(msg);
        } else {
          ElMessage.error("网络或服务器错误，编辑失败");
        }
        return;
      }

      const data = resp && resp.data ? resp.data : resp;
      if (
        data &&
        (data.code === 200 || data.success === true || data.status === 200)
      ) {
        ElMessage.success("护士信息更新成功");
        nurseDialog.visible = false;
        await loadDepartments();
        loadNurses();
      } else {
        const msg = (data && (data.message || data.msg)) || "护士更新失败";
        ElMessage.error(msg);
      }
      return;
    }

    // 新增护士：调用后端 addNurse 接口
    let resp;
    try {
      resp = await addNurse(payload);
    } catch (err) {
      if (err && err.response) {
        const msg =
          err.response.data?.message ||
          err.response.data?.msg ||
          `添加失败（${err.response.status}）`;
        ElMessage.error(msg);
      } else {
        ElMessage.error("网络或服务器错误，添加失败");
      }
      return;
    }

    const data = resp && resp.data ? resp.data : resp;
    if (
      data &&
      (data.code === 200 || data.success === true || data.status === 200)
    ) {
      ElMessage.success("护士添加成功");
      nurseDialog.visible = false;
      // 添加成功后重新加载科室与护士列表（后端真实数据）
      await loadDepartments();
      loadNurses();
    } else {
      const msg = (data && (data.message || data.msg)) || "护士添加失败";
      ElMessage.error(msg);
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const exportData = () => {
  ElMessage.success("数据导出成功");
};

const refreshData = () => {
  loadNurses();
  ElMessage.success("数据已刷新");
};

const formatTitle = (professional_id) => {
  // 优先使用从后端加载的 professionalOptions 查找名称
  const opt = professionalOptions.value.find(
    (p) => Number(p.value) === Number(professional_id)
  );
  if (opt) return opt.label;
};

const formatStatus = (status) => {
  const statusMap = {
    1: "在职",
    2: "休假",
    3: "离职",
  };
  return statusMap[status] || status;
};

const formatSex = (sex) => {
  return sex === 1 ? "男" : sex === 2 ? "女" : "";
};

// 根据科室 id 查 label 的辅助函数（模板使用）
const getDepartmentLabel = (id) => {
  const d = departmentOptions.value.find((x) => Number(x.value) === Number(id));
  return d ? d.label : id;
};

// 状态对应的 tag 类型（模板使用）
const statusTagType = (status) =>
  status === 1 ? "success" : status === 2 ? "warning" : "info";

// 捕获并忽略 ResizeObserver 相关的循环通知错误，避免 dev overlay 报错
const _handleResizeObserverError = (event) => {
  if (
    event &&
    typeof event.message === "string" &&
    event.message.indexOf("ResizeObserver loop") !== -1
  ) {
    if (typeof event.stopImmediatePropagation === "function") {
      event.stopImmediatePropagation();
    }
  }
};

// 获取科室类型列表
const loadDepartmentTypes = async () => {
  try {
    const res = await getDepartmentTypeList();
    if (res && res.code === 200) {
      departmentTypes.value =
        res.data.filter(
          (dept) =>
            dept.department_type_id === 1 || dept.department_type_id === 2
        ) || [];
    } else {
      console.warn("获取科室类型列表失败，使用默认数据");
    }
  } catch (error) {
    console.error("获取科室类型列表出错:", error);
  }
};

// 初始加载科室与护士数据
onMounted(async () => {
  await loadDepartmentTypes(); // 新增
  await loadDepartments();
  await loadProfessionalTitles();
  loadNurses();
});

// 清理监听器，避免内存泄漏
onUnmounted(() => {
});
</script>

<style lang="scss" scoped>
/* 内容区域样式 */
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0; // 添加这行
  min-height: 100%; // 添加这行
  overflow-y: auto; // 确保有这行
}

.filter-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.nurse-table {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.nurse-info {
  display: flex;
  align-items: center;
}

.nurse-avatar {
  margin-right: 12px;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  .el-avatar {
    border: 1px solid #ebeef5;
    background: #f5f7fa;
  }
}

// 抽屉自定义头部
.drawer-custom-header {
  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
  }
}

.drawer-content-wrapper {
  padding: 0 20px;
  height: 100%;
  overflow-y: auto;
}

// 个人信息卡片 - 护士风格渐变
.staff-profile-card {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
  }
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
  z-index: 1;
}

.profile-avatar {
  border: 3px solid rgba(255, 255, 255, 0.2);
}

.profile-info {
  flex: 1;
  
  .staff-name {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: white;
  }
  
  .staff-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
    
    .work-id {
      font-size: 14px;
      opacity: 0.9;
    }
  }
}

// 详细信息区域
.detail-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
  
  .el-icon {
    color: #52c41a;
    font-size: 16px;
  }
  
  span {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.section-content {
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }
  
  .info-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    label {
      font-size: 13px;
      color: #909399;
      font-weight: 500;
    }
    
    span {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
      
      &.username {
        color: #52c41a;
        font-family: 'Courier New', monospace;
      }
      
      &.highlight {
        color: #52c41a;
        font-weight: 600;
      }
    }
  }
  
  .info-item-full {
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    label {
      font-size: 13px;
      color: #909399;
      font-weight: 500;
    }
    
    .info-content {
      font-size: 14px;
      color: #303133;
      line-height: 1.5;
      
      &.description-text {
        background: #f8f9fa;
        padding: 16px;
        border-radius: 8px;
        border-left: 4px solid #52c41a;
        min-height: 60px;
      }
    }
  }
}

// 抽屉底部
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

// 护士职称样式
:deep(.el-tag) {
  &.el-tag--success {
    background-color: #f6ffed;
    color: #52c41a;
    border-color: #b7eb8f;
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .drawer-custom-header h3 {
    color: #e0e0e0;
  }
  
  .detail-section {
    background: #2d2d2d;
    border-color: #3d3d3d;
  }
  
  .section-header {
    border-bottom-color: #3d3d3d;
    
    span {
      color: #e0e0e0;
    }
  }
  
  .info-item label {
    color: #a0a0a0;
  }
  
  .info-item span {
    color: #e0e0e0;
  }
  
  .info-content {
    color: #e0e0e0;
    
    &.description-text {
      background: #3d3d3d;
      border-left-color: #52c41a;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .drawer-content-wrapper {
    padding: 0 16px;
  }
  
  .profile-header {
    flex-direction: column;
    text-align: center;
  }
  
  .staff-meta {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .section-content .info-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .detail-section {
    padding: 16px;
  }
}
</style>